package jdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 使用PreparedStatement代替Statement,防止SQL注入破坏服务器
 * 相当于在获取执行对象的时候就用sql语句预编译,免得被注入的sql影响
 */
public class PreparedStatementDemo {
    public static void main(String[] args) {

    }
    @Test
    public void testPreparedStatement() throws Exception{
        String url = "jdbc:mysql:///test?useSSL=false";
        String username = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url, username, password);

        //接受用户输入的用户名和密码
        String name = "zhangsan";
        String pwd = "' or '1' = '1";

        String sql = "select * from user where username = ? and password = ?";
        //获取pstmt对象
        PreparedStatement pstmt = con.prepareStatement(sql);
        //设置?的值
        pstmt.setString(1,name);
        pstmt.setString(2,pwd);
        //执行sql,sql语句作为参数,因为已经预编译过了
        ResultSet rs = pstmt.executeQuery();
        if(rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登陆失败~");
        }

        //释放资源
        rs.close();
        pstmt.close();
        con.close();
    }
}
